package com.zhkc.iess.online.test01.handler;

import com.zhkc.iess.online.test01.core.HJ212Data;
import com.zhkc.iess.online.test01.service.ChannelRemotingService;
import com.zhkc.iess.online.test01.service.HJ212Service;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class NettyServerHandler2 extends SimpleChannelInboundHandler<HJ212Data> {

    private final ChannelRemotingService channelRemotingService;
    private final HJ212Service hj212Service;

    public NettyServerHandler2(ChannelRemotingService channelRemotingService, HJ212Service hj212Service) {
        System.out.println(1);
        this.channelRemotingService = channelRemotingService;
        this.hj212Service = hj212Service;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println(2);
        channelRemotingService.addConnectionEntry(ctx.channel());
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println(3);
        channelRemotingService.removeConnection(ctx.channel().id());
        ctx.fireChannelInactive();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HJ212Data msg) {
        System.out.println(4);
        log.info("收到客户端发来的消息：{}", msg.toString());
//        Channel channel = ctx.channel();

        ctx.channel().attr(HJ212Data.ST_ATTR).set(msg.getST());
        ctx.channel().attr(HJ212Data.PW_ATTR).set(msg.getPW());
        ctx.channel().attr(HJ212Data.VERSION_ATTR).set(msg.getVersion());
        ctx.channel().attr(HJ212Data.MN_ATTR).set(msg.getMN());

        //设备MN号和 channel 关联
        channelRemotingService.registerMN(ctx.channel());



        //操作下位机传输的数据（212协议）
        hj212Service.executeHandler(ctx, msg);


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //pipeline里面handler抛出的异常会在这里捕获处理
        log.info("在这里处理异常：{}", cause.getMessage());
    }
}